import { IMiniGame } from "../Number-Jump/scripts/minigame";
import UI_Demo from "./gen/ui/Demo/UI_Demo";

export class Demo {
    constructor(readonly view: UI_Demo, readonly miniGame: IMiniGame) {
        view.m_state.selectedPage = "大厅";
        view.m_loading.m_progress.max = 1;
        view.m_loading.m_progress.value = 0;
        Laya.timer.frameLoop(1, this, () => {
            const dt = Laya.timer.delta / 1000;
            this.update(dt);
            this.fixedUpdate(dt);
            this.constantUpdate(dt);
        });
        view.m_btn_enter.onClick(this, this.onEnterGame);
        view.m_btn_start.onClick(this, this.onStartGame);
        view.m_btn_exit.onClick(this, this.onExitGame);
        view.m_btn_finish.onClick(this, this.onFinishGame);
        view.m_btn_revive.onClick(this, this.onRevive);
        view.m_btn_home.onClick(this, this.onReturnHome);
    }

    update(dt: number) {
        this.miniGame.update(dt);
    }
    fixedUpdate(dt: number) {
        this.miniGame.fixedUpdate(dt);
    }
    constantUpdate(dt: number) {
        this.miniGame.constantUpdate(dt);
    }

    async onEnterGame() {
        this.view.m_state.selectedPage = "加载中";
        await this.miniGame.loadGame((progress: number) => {
            console.log(progress);
            this.view.m_loading.m_progress.value = progress;
        });
        this.view.m_state.selectedPage = "小游戏主页";
        this.miniGame.view.m_state.selectedIndex = 0;
        this.view.m_layer.displayObject.addChild(this.miniGame.view.displayObject);

        // this.miniGame.load 是否需要在之前 加载存储数据？？？
        // onReady之前需给miniGame.stage赋值，非关卡制的赋值1
        this.miniGame.onReady();
    }

    onExitGame() {
        // this.miniGame.pauseGame();
        this.miniGame.view.removeFromParent();
        // this.miniGame.view.dispose();
        this.miniGame.unloadGame();
        this.view.m_state.selectedPage = "大厅";
    }

    onStartGame() {
        this.miniGame.startGame();
        this.miniGame.view.m_state.selectedIndex = 1;
        this.view.m_state.selectedPage = "游戏中";
    }

    onFinishGame() {
        // 结算之前需给miniGame.score赋值
        this.miniGame.tryFinish();
        this.miniGame.view.m_state.selectedIndex = 2;
        this.view.m_state.selectedPage = "游戏结算";
    }

    onRevive() {
        this.miniGame.continueGame();
        this.miniGame.view.m_state.selectedIndex = 1;
        this.view.m_state.selectedPage = "游戏中";
    }

    onReturnHome() {
        this.miniGame.endGame();
        this.view.m_state.selectedPage = "小游戏主页";
        this.miniGame.view.m_state.selectedIndex = 0;
        // onReady之前需给miniGame.stage赋值，非关卡制的赋值1
        this.miniGame.onReady();
    }
}
